import React from "react";
import { useAppSelector, useAppDispatch } from "../redux/store";
import { loginAction, addAction, logoutAction, clearAction } from "../redux/actions";
import { UserAction, CartAction } from '../redux/types';
 
const Dashboard: React.FC = () => {
  // 1. 使用带类型的 useAppSelector 获取状态（自动提示 RootState 的属性）
  const { name } = useAppSelector((state) => state.user); // 类型：string | null
  const { items, total } = useAppSelector((state) => state.cart); // 类型：string[] 和 number
 
  // 2. 使用带类型的 useAppDispatch 获取 dispatch 函数
  const dispatch = useAppDispatch();
 
  // 3. 定义触发动作的函数（类型自动校验）
  const handleLogin = () => {
    // 正确的 action 类型（自动提示 type 和 payload）
    dispatch(loginAction() as UserAction); // 类型匹配，无报错
  };
 
  const handleAddToCart = () => {
    dispatch(addAction() as CartAction);
  };
 
  const handleLogout = () => {
    dispatch(logoutAction() as UserAction);
  };
 
  const handleClearCart = () => {
    dispatch(clearAction() as CartAction);
  };
 
  return (
    <div>
      <h1>用户信息：{name || "未登录"}</h1>
      <button onClick={handleLogin}>登录</button>
      <button onClick={handleLogout}>退出</button>
 
      <h2>购物车</h2>
      <p>商品总数：{total}</p>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      <button onClick={handleAddToCart}>添加商品</button>
      <button onClick={handleClearCart}>清空购物车</button>
    </div>
  );
};
 
export default Dashboard;